import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/material.dart';

import 'MyButton.dart';


class GameWrapper extends Component with HasGameRef {
  final Component child;
  final String levelName;
  final int totalTime;
  final Function() onPaused;
  final Function() onHome;
  final double topPadding;

  late TextComponent _levelText;
  late TextComponent _timerText;
  late TextComponent _scoreText;
  late MyButton _pauseButton;
  // 移除 _homeButton 的声明

  int _currentTime;
  int _score = 0;
  int targetScore; // 移除默认值，从构造函数获取
  late Timer _timer;
  bool _isPaused = false; // 添加暂停状态

  GameWrapper({
    required this.child,
    required this.levelName,
    required this.totalTime,
    required this.targetScore, // 添加targetScore参数
    required this.onPaused,
    required this.onHome,
    this.topPadding = 0, // 默认为0，保持向后兼容
  }) : _currentTime = totalTime {
    _timer = Timer(1, repeat: true, onTick: _updateTimer);
  }

  @override
  Future<void> onLoad() async {
    super.onLoad();

    // 添加整体背景颜色
    final background = RectangleComponent(
      size: gameRef.size,
      paint: Paint()..color = const Color(0xFF22AFF1),
    );
    add(background);

    // 添加子组件
    add(child);

    // 创建顶部UI区域背景，考虑安全区
    final topBar = RectangleComponent(
      size: Vector2(gameRef.size.x, 80 + topPadding), // 增加高度以容纳纵向排列的元素
      position: Vector2(0, 0),
      paint: Paint()..color = const Color(0x80000000), // 半透明黑色背景
    );
    add(topBar);

    // 添加关卡信息，考虑安全区
    _levelText = TextComponent(
      text: '关卡: $levelName',
      textRenderer: TextPaint(
        style: TextStyle(
          color: Colors.white,
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),
      position: Vector2(20, 10 + topPadding),
    );
    add(_levelText);


    _scoreText = TextComponent(
      text: targetScore-_score>=0? '剩余分数:${targetScore-_score}' : '恭喜成功！',
      textRenderer: TextPaint(
        style: TextStyle(
          color: Colors.white,
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),
      position: Vector2(20, 35 + topPadding),
    );
    add(_scoreText);

    _timerText = TextComponent(
      text: '时间: $_currentTime',
      textRenderer: TextPaint(
        style: TextStyle(
          color: _currentTime <= 10 ? Colors.red : Colors.white,
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),
      position: Vector2(20, 60 + topPadding),
    );
    add(_timerText);

    // 移除主页按钮

    // 添加暂停按钮，考虑安全区
    _pauseButton = MyButton(
      text: '暂停',
      onPressed: togglePause, // 修改为公共方法
      position: Vector2(gameRef.size.x - 100, 10 + topPadding),
    );
    add(_pauseButton);

    // 启动计时器
    _timer.start();
  }

  void _updateTimer() {
    if (_currentTime > 0) {
      _currentTime--;
      _timerText.text = '时间: $_currentTime';

      
      // 检查是否达到目标分数
      if (_score >= targetScore) {
        // 玩家成功完成游戏
        _timer.stop();
        gameRef.overlays.add('gameOver');
      }
    } else {
      // 时间结束逻辑
      _timer.stop();
      // 显示游戏结束弹窗
      gameRef.overlays.add('gameOver');
    }
  }

  @override
  void update(double dt) {
    super.update(dt);
    if (!_isPaused) { // 只有在非暂停状态才更新计时器
      _timer.update(dt);
    }
  }

  // 获取当前剩余时间
  int getCurrentTime() => _currentTime;

  // 获取当前得分
  int getScore() => _score;
  
  // 获取目标得分
  int getTargetScore() => targetScore;

  // 增加得分
  void addScore(int points) {
    _score += points;
    _scoreText.text = _score >= targetScore ? '恭喜成功！' : '剩余分数:${targetScore - _score}';
    
    // 检查是否达到目标分数，但仅在时间未结束时显示游戏结束弹窗
    if (_score >= targetScore && _currentTime > 0) {
      gameRef.overlays.add('gameOver');
    }
  }

  // 重置得分
  void resetScore() {
    _score = 0;
    _scoreText.text = targetScore-_score>=0? '剩余分数:${targetScore-_score}' : '恭喜成功！';
  }

  // 重置计时器
  void resetTimer() {
    _currentTime = totalTime;
    _timerText.text = '时间: $_currentTime';
    _isPaused = false; // 重置时取消暂停状态
    _pauseButton.textComponent.text = '暂停'; // 重置按钮文本
  }

  // 暂停计时器
  void pauseTimer() {
    _timer.stop();
  }

  // 恢复计时器
  void resumeTimer() {
    _timer.start();
  }

  // 切换暂停状态（公共方法）
  void togglePause() {
    _isPaused = !_isPaused;
    if (_isPaused) {
      pauseTimer();
      FlameAudio.bgm.pause();
      _pauseButton.textComponent.text = '继续';
      // 显示暂停弹窗
      gameRef.overlays.add('pause');
    } else {
      resumeTimer();
      _pauseButton.textComponent.text = '暂停';
      // 移除暂停弹窗
      FlameAudio.bgm.resume();
      gameRef.overlays.remove('pause');
    }
    // 调用外部传入的暂停回调
    onPaused();
  }

  // 获取暂停状态
  bool isPaused() => _isPaused;
  
}